<template>
  <div class="book-form">
    <div class="page-card">
      <div class="page-header">
        <h1 class="page-title">{{ isEdit ? '编辑图书' : '添加图书' }}</h1>
      </div>

      <div class="page-content">
        <div class="form-container">
          <el-form ref="bookFormRef" :model="bookForm" :rules="bookRules" label-width="100px" @submit.prevent>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="书名" prop="title">
                  <el-input v-model="bookForm.title" placeholder="请输入书名" maxlength="100" show-word-limit />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="作者" prop="author">
                  <el-input v-model="bookForm.author" placeholder="请输入作者" maxlength="50" show-word-limit />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="ISBN" prop="isbn">
                  <el-input v-model="bookForm.isbn" placeholder="请输入ISBN" maxlength="20" />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="分类" prop="categoryId">
                  <el-select v-model="bookForm.categoryId" placeholder="请选择分类" style="width: 100%">
                    <el-option v-for="category in categories" :key="category.id" :label="category.name"
                      :value="category.id" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出版社" prop="publisher">
                  <el-input v-model="bookForm.publisher" placeholder="请输入出版社" maxlength="50" show-word-limit />
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="出版日期" prop="publishDate">
                  <el-date-picker v-model="bookForm.publishDate" type="date" placeholder="请选择出版日期" style="width: 100%"
                    format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="总数量" prop="totalCopies">
                  <el-input-number v-model="bookForm.totalCopies" :min="1" :max="9999" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="可借数量" prop="availableCopies">
                  <el-input-number v-model="bookForm.availableCopies" :min="0" :max="bookForm.totalCopies || 9999"
                    style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="8">
                <el-form-item label="价格" prop="price">
                  <el-input-number v-model="bookForm.price" :min="0" :precision="2" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="封面图片">
              <div class="cover-upload">
                <div class="cover-preview">
                  <img v-if="bookForm.coverUrl" :src="bookForm.coverUrl" alt="封面预览" />
                  <div v-else class="default-cover">
                    <el-icon size="48">
                      <Picture />
                    </el-icon>
                    <p>暂无封面</p>
                  </div>
                </div>
                <div class="cover-actions">
                  <el-input v-model="bookForm.coverUrl" placeholder="请输入封面图片URL" style="margin-bottom: 8px" />
                  <el-button size="small" @click="clearCover">清除封面</el-button>
                </div>
              </div>
            </el-form-item>

            <el-form-item label="简介">
              <el-input v-model="bookForm.description" type="textarea" :rows="4" placeholder="请输入图书简介" maxlength="500"
                show-word-limit />
            </el-form-item>

            <div class="form-actions">
              <el-button @click="$router.back()">取消</el-button>
              <el-button type="primary" @click="handleSubmit" :loading="submitting">
                {{ isEdit ? '更新' : '创建' }}
              </el-button>
            </div>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getBookDetail, createBook, updateBook } from '@/api/book'
import { getAllCategories } from '@/api/category'
import { Picture } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 表单引用
const bookFormRef = ref()

// 加载状态
const submitting = ref(false)

// 是否编辑模式
const isEdit = computed(() => !!route.params.id)

// 分类列表
const categories = ref([])

// 图书表单
const bookForm = reactive({
  title: '',
  author: '',
  isbn: '',
  categoryId: '',
  publisher: '',
  publishDate: '',
  totalCopies: 1,
  availableCopies: 1,
  price: 0,
  coverUrl: '',
  description: ''
})

// 表单验证规则
const bookRules = {
  title: [
    { required: true, message: '请输入书名', trigger: 'blur' },
    { min: 1, max: 100, message: '书名长度在 1 到 100 个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' },
    { min: 1, max: 50, message: '作者长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  isbn: [
    { required: true, message: '请输入ISBN', trigger: 'blur' },
    { pattern: /^[0-9-]+$/, message: 'ISBN只能包含数字和连字符', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  publisher: [
    { required: true, message: '请输入出版社', trigger: 'blur' },
    { min: 1, max: 50, message: '出版社长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  publishDate: [
    { required: true, message: '请选择出版日期', trigger: 'change' }
  ],
  totalCopies: [
    { required: true, message: '请输入总数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '总数量必须大于0', trigger: 'blur' }
  ],
  availableCopies: [
    { required: true, message: '请输入可借数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '可借数量不能小于0', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格不能小于0', trigger: 'blur' }
  ]
}

// 加载分类列表
const loadCategories = async () => {
  try {
    const response = await getAllCategories()
    categories.value = response.data
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 加载图书详情（编辑模式）
const loadBookDetail = async () => {
  if (!isEdit.value) return

  try {
    const response = await getBookDetail(route.params.id)
    const book = response.data

    // 填充表单
    Object.assign(bookForm, {
      title: book.title,
      author: book.author,
      isbn: book.isbn,
      categoryId: book.categoryId,
      publisher: book.publisher,
      publishDate: book.publishDate,
      totalCopies: book.totalCopies,
      availableCopies: book.availableCopies,
      price: book.price,
      coverUrl: book.coverUrl || '',
      description: book.description || ''
    })
  } catch (error) {
    console.error('加载图书详情失败:', error)
    ElMessage.error('加载图书信息失败')
    router.back()
  }
}

// 清除封面
const clearCover = () => {
  bookForm.coverUrl = ''
}

// 提交表单
const handleSubmit = async () => {
  if (!bookFormRef.value) return

  try {
    await bookFormRef.value.validate()

    // 验证可借数量不能大于总数量
    if (bookForm.availableCopies > bookForm.totalCopies) {
      ElMessage.error('可借数量不能大于总数量')
      return
    }

    submitting.value = true

    if (isEdit.value) {
      await updateBook(route.params.id, bookForm)
      ElMessage.success('更新图书成功')
    } else {
      await createBook(bookForm)
      ElMessage.success('创建图书成功')
    }

    router.push('/books')
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitting.value = false
  }
}

// 初始化
onMounted(() => {
  loadCategories()
  loadBookDetail()
})
</script>

<style scoped>
.book-form {
  max-width: 800px;
  margin: 0 auto;
}

.cover-upload {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.cover-preview {
  width: 120px;
  height: 160px;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: #fafafa;
}

.cover-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  text-align: center;
  color: #999;
}

.default-cover p {
  margin: 8px 0 0 0;
  font-size: 12px;
}

.cover-actions {
  flex: 1;
}

@media (max-width: 768px) {
  .cover-upload {
    flex-direction: column;
  }

  .cover-preview {
    width: 100px;
    height: 133px;
    align-self: center;
  }
}
</style>